package com.wgj.android.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jiaai.xui.XUI;
import com.jiaai.xui.cache.XCache;
import com.jiaai.xui.utils.XEmptyUtils;
import com.jiaai.xui.utils.XPreferencesUtils;
import com.jiaai.xui.utils.XThemeUtils;
import com.jiaai.xui.utils.http.HttpCallBack;
import com.jiaai.xui.utils.http.XHttp;
import com.jiaai.xui.utils.log.XLog;
import com.jiaai.xui.view.widget.XToast;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.wgj.android.R;
import com.wgj.android.entity.Member;
import com.wgj.android.http.WGJAPI;
import com.wgj.android.http.model.AccessToken;
import com.wgj.android.utils.CacheUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * ========================================
 * 作    者： 佳爱网络有限公司(wwww.jiaailove.com)
 * 版    本： 1.0
 * 创建日期：  2017/12/6
 * 描    述：  登录主页
 * 修订历吏：
 * =========================================
 */
public class LoginActivity extends AppCompatActivity {

    @BindString(R.string.server_error)
    String  serverError;
    @BindView(R.id.phoneEdit)
    EditText phoneEdit;

    @BindView(R.id.evPassword)
    EditText evPassword;

    @BindView(R.id.resetPs)
    TextView resetPs;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.login_activity);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
    }


    /**
     * 登录
     * @param view
     */
    @OnClick(R.id.loginBut)
    public void  onLogin(final View view){
        String phone=phoneEdit.getText().toString();
        String passowd=evPassword.getText().toString();
        if(XEmptyUtils.isSpace(phone)){
            XToast.error("请输入手机号码");
            return;
        }
        if(XEmptyUtils.isSpace(passowd)){
            XToast.error("密码不能为空");
            return;
        }
        Map<String,Object> params=new HashMap<>();
        params.put("phone",phone);
        params.put("password",passowd);
        ((Button)view).setText("登录中...");
        XHttp.obtain().post(WGJAPI.LOGIN_URL, params, new HttpCallBack<String>() {
            @Override
            public void onSuccess(String s) {
                ((Button)view).setText("登录");
                AccessToken accessToken = null;
                try {
                    JSONObject js = new JSONObject(s);
                     accessToken = new AccessToken();
                    accessToken.setId(js.getString("id"));
                    accessToken.setToken(js.getString("token"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                
                CacheUtils.cacheToken(accessToken);
                Member.init(accessToken.getId(), new HttpCallBack<Member>() {
                    @Override
                    public void onSuccess(Member member) {
                        try {
                            CacheUtils.setMember(member);
                        }catch (Exception e){

                        }
                        Intent intent=new Intent(getApplication(), MainActivity.class);
                        startActivity(intent);
                        finish();
                    }

                    @Override
                    public void onFailed(int i, String s, boolean b) {
                        ((Button)view).setText("登录");
                        XToast.error("登录失败");
                    }
                });
            }

            @Override
            public void onFailed(int i, String s, boolean b) {
                ((Button)view).setText("登录");
                XToast.error("请检查你的帐号是否正确");
            }
        });

    }
    /**
     * 找回密码
     * @param view
     */
    @OnClick(R.id.resetPs)
    public void resetPassword(View view){
        Intent intent = new Intent(this,FindPwdActivity.class);
        startActivityForResult(intent,1);
    }
    @OnClick(R.id.image)
    public void onClickWX(View view){
        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wxlogin";
        WXAPIFactory.createWXAPI(this,
                "wxbcb3914d8111c047", false).sendReq(req);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==RESULT_OK){
            phoneEdit.setText(data.getStringExtra("phone"));
        }

    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void WXCode(SendAuth.Resp resp){
        Map params = new HashMap<String,Object>();
        params.put("code",resp.code);
        XHttp.obtain().post(WGJAPI.WXLOGIN_URL, params, new HttpCallBack<String>() {
            @Override
            public void onSuccess(String s) {
                AccessToken accessToken = null;
                try {
                    JSONObject js = new JSONObject(s);
                    accessToken = new AccessToken();
                    accessToken.setId(js.getString("id"));
                    accessToken.setToken(js.getString("token"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                CacheUtils.cacheToken(accessToken);
                Member.init(accessToken.getId(), new HttpCallBack<Member>() {
                    @Override
                    public void onSuccess(Member member) {
                        try {
                            CacheUtils.setMember(member);
                        }catch (Exception e){

                        }
                        Intent intent=new Intent(getApplication(), MainActivity.class);
                        startActivity(intent);
                        finish();
                    }

                    @Override
                    public void onFailed(int i, String s, boolean b) {
                        //((Button)view).setText("登录");
                        XToast.error("登录失败");
                    }
                });
            }

            @Override
            public void onFailed(int i, String s, boolean b) {
                XToast.error("登录失败");
            }
        });
    }


}
